import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo, getUserDetailById } from '@/api/user'

export default {
  namespaced: true,
  state: {
    token: '' || getToken(), // 优先从本地存储获取token  // 保存token
    info: {} // 储存用户信息
  },
  mutations: {
    // 更新token
    updateToken(state, token) {
      state.token = token
      // 进行token持久化
      setToken(token)
    },
    // 删除token
    removeToken(state, token) {
      state.token = ''
      removeToken()
    },
    // 更新用户信息
    updateInfo(state, info) {
      state.info = info
    },
    removeInfo(state, info) {
      state.info = {}
    }
  },
  actions: {
    async userLogin(context, loginForm) {
      try {
        const res = await login(loginForm)
        context.commit('updateToken', res.data)
      } catch (error) {
        console.log(error)
      }
    },
    async getUserInfo(context) {
      try {
        const res = await getInfo()
        // console.log(res.data.userid)
        const info = await getUserDetailById(res.data.userId)
        // console.log('info', info)
        context.commit('updateInfo', { ...res.data, ...info.data })
      } catch (error) {
        console.log(error)
      }
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeInfo')
    }
  }
}
